<?php


Class DB
{

    private $_config = './config.php';

    private $link_id;

    public function __construct()
    {
        $db_config = $this->addConfig('db');
        $this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]);
    }


    public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0,$charset='utf8')
    {
        if( $pconnect==0 ) {
            $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
            if(!$this->link_id){
                $this->_halt("数据库连接失败");
            }
        } else {
            // 持久性连接
            $this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw);
            if(!$this->link_id){
                $this->_halt("数据库持久连接失败");
            }
        }

        // 设置活动的 MySQL 数据库
        if(!@mysql_select_db($dbname,$this->link_id)) {
            $this->_halt('数据库选择失败');
        }
        @mysql_query("set names ".$charset);
    }


    public function insert($data,$tableName)
    {

        if(is_array($data)){

            $field = implode("','",array_keys($data));
            $value = "'".implode("','",array_values($data))."'";
        }
        $value = $this->_encoding($value);
        $sql   = "INSERT INTO $tableName($field) VALUES($value)";

        $query = mysql_query($sql);

        if($query) {
            return $query;
        } else{
            return $this->_halt();
        }

    }


    public function addConfig($num='')
    {
         $data = include $this->_config;
         return $data[$num];
    }


    private function _halt($msg='')
    {
        header("Content-Type: text/html; charset=UTF-8");
        $msg .= "<br>error:".mysql_error();
        exit($msg);
    }


    private function _encoding($str)
    {
        foreach (array('GBK', 'UTF-8') as $v) {

            if ($str === iconv($v, $v . '//IGNORE', $str)) {
               return iconv($v, 'UTF-8//IGNORE', $str);
            }
        }


    }


}

